package com.xunji.xunji.module.trace.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.huanxiao.base.base.BaseActivity;
import com.huanxiao.base.common.bean.EventMessage;
import com.huanxiao.base.net.RespResult;
import com.huanxiao.base.util.AlertDialogUtil;
import com.huanxiao.base.util.FileHelper;
import com.huanxiao.base.util.PathHelper;
import com.huanxiao.util.ToastHelper;
import com.xunji.xunji.R;
import com.xunji.xunji.module.account.controller.UserAccount;
import com.xunji.xunji.module.account.ui.activity.LoginActivity;
import com.xunji.xunji.module.trace.util.PointConst;
import com.xunji.xunji.module.trace.controller.TraceManager;
import com.xunji.xunji.module.trace.dao.TraceImage;
import com.xunji.xunji.module.trace.en.TraceTypeEnum;
import com.xunji.xunji.module.trace.util.MapUtils;
import com.xunji.xunji.module.trace.util.SensorEventHelper;
import com.xunji.xunji.ui.view.TracePictureImageView;

import java.io.File;
import java.util.List;

import rx.Subscriber;

/**
 * Created by Paul on 2017/2/8.
 */

public class TraceMapActivity extends BaseActivity implements
        LocationSource, AMapLocationListener, View.OnClickListener, AMap.OnMarkerClickListener {

    private static final int REQUEST_CODE_IMAGE_FROM_CAMERA = 1;
    private static final int REQUEST_CODE_CROP_IMAGE = 3;//启动裁剪编辑


    private TextView tvLatitude;
    private TextView tvLongitude;
    private TextView tvHeight;
    private Button btnStart;
    private Button btnStop;
    private Button btnPause;
    private ImageView ivPicture;
    private RelativeLayout rlOnGoing;
    private ImageView ivLocate;

    private TextView tvStartTime;


    private TraceManager traceManager;


    public static void start(Context context) {
        Intent starter = new Intent(context, TraceMapActivity.class);
        context.startActivity(starter);
    }

    private boolean mFirstFix = true;

    private Marker mLocMarker;
    private Marker mStartMarker;
    private Marker mStopMarker;

    private AMap aMap;
    private MapView mMapView = null;
    private UiSettings mUiSettings;
    private SensorEventHelper mSensorHelper;

    public static final String LOCATION_MARKER_FLAG = "mylocation";
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private LatLng mCurrentLatlng;

    private double mCurrentAltitude = 0;

    private LatLng mOldLatlng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);

        init();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case REQUEST_CODE_IMAGE_FROM_CAMERA:
                Uri tempPicUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg"));
                cropImage(tempPicUri);
                break;
            case REQUEST_CODE_CROP_IMAGE:
                try {
                    Bitmap mPhotoBitmap = data.getParcelableExtra("data");
                    if (mPhotoBitmap == null) {
                        Uri uri = data.getData();
                        mPhotoBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                    }
                    if (mPhotoBitmap == null) {
                        return;
                    }
                    String fileName = "point_" + System.currentTimeMillis() + ".png";
                    FileHelper.saveBitmapToFile(mPhotoBitmap, fileName);

                    TracePhotoEditActivity.start(this, PathHelper.getLocalProductImagePath() + fileName, mCurrentLatlng.latitude, mCurrentLatlng.longitude, traceManager.getTraceId());

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();

        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }

        traceManager.reset();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_trace_map;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    public void initBundleExtras(Bundle extras) {

    }

    @Override
    protected void initView() {
        tvLatitude = fvById(R.id.tv_latitude);
        tvLongitude = fvById(R.id.tv_longitude);
        tvHeight = fvById(R.id.tv_height);
        btnStart = fvById(R.id.btn_start_trace);
        btnStop = fvById(R.id.btn_stop_trace);
        btnPause = fvById(R.id.btn_pause_trace);

        tvStartTime = fvById(R.id.tv_start_time);
        rlOnGoing = fvById(R.id.rl_on_going);
        ivPicture = fvById(R.id.iv_capture);
        ivLocate = fvById(R.id.iv_locate);
    }

    @Override
    protected void initListener() {
        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        tvStartTime.setOnClickListener(this);
        ivPicture.setOnClickListener(this);
        ivLocate.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
    }

    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.e("HPG", "onLocationChanged");
        if (mListener != null) {

            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                LatLng location = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                mCurrentLatlng = location;

                tvLatitude.setText(location.latitude + "");
                tvLongitude.setText(location.longitude + "");
                tvHeight.setText(aMapLocation.getAltitude() + "");
                mCurrentAltitude = aMapLocation.getAltitude();


                if (mFirstFix) {
                    mOldLatlng = mCurrentLatlng;
                    mFirstFix = false;
//                    mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                    changeCamera(location, null);
                    mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点

                }

//                addMarker(location);//添加定位图标
//                else {
//                    changeCamera(location, null);
//                }


                //如果是不同点，则记录
                if (!MapUtils.isSamePoint(mOldLatlng, mCurrentLatlng)) {

                    //暂停情况不连线
                    if (traceManager.isStart()) {
                        //连线
                        addLine(mOldLatlng, mCurrentLatlng);
                        //保存点到临时变量
                        traceManager.savePoint(location, mCurrentAltitude, TraceTypeEnum.NORMAL_POINT.getType());
                        //更新老的点
                        mOldLatlng = mCurrentLatlng;
                    }

                }
            } else {
                Log.e("amapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }

        }
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        Log.e("HPG", "OnLocationChangedListener");
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();

        }
    }


    @Override
    public void onEventBusListener(EventMessage message) {
        super.onEventBusListener(message);
        if (message.getTag() == EVENT_TRACE_IMAGE_SAVE) {
            addPictureMarker((TraceImage) message.getData());
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 初始化AMap对象
     */

    private void init() {

        mSensorHelper = new SensorEventHelper(this);
        traceManager = TraceManager.getInstance();
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
        if (aMap == null) {
            aMap = mMapView.getMap();
            mUiSettings = aMap.getUiSettings();
//            mUiSettings.setScaleControlsEnabled(true);
            setUpMap();
        }
        aMap.setLocationSource(this);// 设置定位监听
        mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setScaleControlsEnabled(true);
        aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层

    }


    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.navi_map_gps_locked));// 设置小蓝点的图标
//        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(190,255,222,173));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setOnMarkerClickListener(this);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false


    }

    /**
     * 移动到这个位置
     *
     * @param latLng
     * @param callback
     */
    private void changeCamera(LatLng latLng, AMap.CancelableCallback callback) {
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                latLng, 15, 0, 15));
        if (true) {
            aMap.animateCamera(update, 500, callback);
        } else {
            aMap.moveCamera(update);
        }
    }
    double x=0;

    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {
            mLocMarker.remove();
        }

        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.navi_map_gps_locked);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
        mLocMarker.setTitle(LOCATION_MARKER_FLAG);
        mSensorHelper.setCurrentMarker(mLocMarker);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_start_trace:
                if (!UserAccount.getInstance().isLogin()) {
                    ToastHelper.showMessage("请先登录");
                    LoginActivity.start(this);
                } else {

                    startTrace();
                    addStartMarker(mCurrentLatlng);
                }
                break;
            case R.id.btn_stop_trace:
                AlertDialogUtil.showDialog(this, "提示", "确定结束轨迹记录？", "取消", "确定", null, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AlertDialogUtil.showEditDialog(TraceMapActivity.this, "请输入轨迹名称", "", "", "确定", new AlertDialogUtil.OnFinishClickListener() {

                            @Override
                            public void onFinishListener(int position, String strs, Dialog dialog) {

                                stopTrace(strs);
                                addStopMarker(mCurrentLatlng);
                            }
                        });

                    }
                });


                break;

            case R.id.btn_pause_trace:
                pauseTrace();
                break;

            case R.id.tv_start_time:

                break;

            case R.id.iv_capture:
                getFromCamera();
//                TracePhotoEditActivity.start(this);
                break;

            case R.id.iv_locate:
                changeCamera(mCurrentLatlng, null);
                break;
        }
    }

    private void showEdit() {

    }

    /**
     * 多段颜色（非渐变色）
     */
    private void addPolylinesWithColors() {
        //四个点
//        LatLng A = new LatLng(Lat_A + 0.0001, Lon_A + 0.0001);
//        LatLng B = new LatLng(Lat_B + 0.0001, Lon_B + 0.0001);
//        LatLng C = new LatLng(Lat_C + 0.0001, Lon_C + 0.0001);
//        LatLng D = new LatLng(Lat_D + 0.0001, Lon_D + 0.0001);
//        LatLng E = new LatLng(Lat_D + 0.0002, Lon_D + 0.0002);

        //用一个数组来存放颜色，四个点对应三段颜色
//        List<Integer> colorList = new ArrayList<Integer>();
//        colorList.add(Color.RED);
//        colorList.add(Color.YELLOW);
//        colorList.add(Color.GREEN);
//		colorList.add(Color.BLACK);

        PolylineOptions options = new PolylineOptions();
//        PolylineOptions options1 = new PolylineOptions();
        options.width(20);//设置宽度


        //加入四个点
//        options.add(A,B,C);
        List<LatLng> latLngs = traceManager.getLatlngList();
        options.addAll(latLngs);
        options.color(Color.RED);

        aMap.addPolyline(options);

//
//        options1.add(C,D,E);
//        options1.color(Color.YELLOW);
//        aMap.addPolyline(options1);
    }

    /**
     * 绘制两个坐标点之间的线段,从以前位置到现在位置
     */
    private void addLine(LatLng oldData, LatLng newData) {

        // 绘制一个大地曲线
        aMap.addPolyline((new PolylineOptions())
                .add(oldData, newData)
                .geodesic(true).color(Color.RED));

    }


    private void cropImage(Uri tempPicUri) {
        Intent intent = new Intent();
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(tempPicUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
    }

    private void startTrace() {
        traceManager.startTrace(mCurrentLatlng);

        traceManager.savePoint(mCurrentLatlng, mCurrentAltitude, TraceTypeEnum.START_POINT.getType());
        btnStart.setVisibility(View.GONE);
        rlOnGoing.setVisibility(View.VISIBLE);
    }

    private void stopTrace(String title) {
        traceManager.savePoint(mCurrentLatlng, mCurrentAltitude, TraceTypeEnum.STOP_POINT.getType());
        traceManager.stopTrace(mCurrentLatlng, title);
        btnStart.setVisibility(View.VISIBLE);
        rlOnGoing.setVisibility(View.GONE);

        traceManager.uploadPhoto(title, new Subscriber<RespResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(RespResult respResult) {
//                aMap.getMapScreenMarkers().clear();
//                traceManager.clear();
            }
        });
    }

    private void pauseTrace() {
        if (traceManager.isStart()) {
            btnPause.setText("继续");
            traceManager.pauseTrace(true);
        } else {
            btnPause.setText("暂停");
            traceManager.pauseTrace(false);
        }
    }


    @Override
    public void onBackPressed() {
        if (traceManager.isFinish()) {
            finish();
        } else {
            AlertDialogUtil.showDialog(this, "提示", "退出轨迹记录？", "取消", "确定", null, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                    traceManager.reset();
                }
            });
        }


    }


    /**
     * 开始标记
     *
     * @param latlng
     */
    private void addStartMarker(LatLng latlng) {

        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.ic_start_stop_point);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mStartMarker = aMap.addMarker(options);
        mStartMarker.setTitle(LOCATION_MARKER_FLAG);
    }


    /**
     * 添加停止标记
     *
     * @param latlng
     */
    private void addStopMarker(LatLng latlng) {

        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.navi_map_gps_locked);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mStopMarker = aMap.addMarker(options);
        mStopMarker.setTitle(LOCATION_MARKER_FLAG);
    }


    /**
     * 添加图片标记
     *
     * @param traceImage
     */
    private void addPictureMarker(TraceImage traceImage) {

        Marker pictureMarker;
        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                PointConst.iconMap().get(traceImage.getTag()));
        TracePictureImageView view = new TracePictureImageView(this);
        view.setDrawingCacheEnabled(true);
        view.setTitle(traceImage.getTag());

        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        LatLng latLng = new LatLng(traceImage.getLatitude(), traceImage.getLongitude());
        options.position(latLng);
        pictureMarker = aMap.addMarker(options);
        pictureMarker.setObject(traceImage.getId());
        pictureMarker.setTitle(LOCATION_MARKER_FLAG);
    }

    private void getFromCamera() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg"));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_CAMERA);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onMarkerClick(Marker marker) {


        TraceImage image = traceManager.getTraceImageById((Integer) marker.getObject());

        ToastHelper.showMessage(image != null ? image.getContent() : "");


        return true;
    }
}
